<?php

namespace app\admin\controller\order;

use app\admin\model\order\OrderGoods;
use app\admin\model\OrderRefund;
use app\common\controller\Backend;
use app\common\model\Config;
use think\Db;
use app\admin\model\order\Order as OrderModel;
use app\admin\model\order\Sale as SaleModel;
use wxpay\Wechat;
/**
 * 售后管理
 *
 * @icon fa fa-circle-o
 */
class Sale extends Backend
{

    /**
     * Sale模型对象
     * @var \app\admin\model\order\Sale
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Sale;

        $this->view->assign('statusList',$this->model->getStatusList());
        $this->view->assign('typeList',$this->model->getTypeList());
        $this->view->assign('refundtypelist',$this->model->getRefundTypeList());


    }

    public function index()
    {
        //是否关联
        $this->relationSearch = true;
        //     if (false === $this->request->isAjax()) {
        //     return $this->view->fetch();
        // }
        $name = $this->request->param('name', '');
        $status = $this->request->param('status', '');
        $createtime = $this->request->param('createtime', 0);
        $endtime = $this->request->param('endtime', 0);
        $page = $this->request->param('page', 1);
        $searname = $this->request->param('searname', '');
        $refundName = $this->request->param('refundName', '');
        $serialNum = $this->request->param('SerialNum', '');
        $name_keyword = $this->request->param('name_keyword', '');

        $createtime = strtotime($createtime);
        $endtime = strtotime($endtime);

        $where = [];

        if (!empty($status)) {
            $where['status'] = ['eq', $status];
        }
        if (!empty($refundName)) {
            $where['refund_reason'] = ['eq', $refundName];
        }
        if ($createtime && $endtime) {
            $where['sale.create_time'] = array(['>=', $createtime], ['<=', $endtime], 'and');
        } elseif ($createtime) {
            $where['create_time'] = ['>=', $createtime];
        } elseif ($endtime) {
            $where['create_time'] = ['<=', $endtime];
        }
        if (!empty($searname))
        {
            $where['phone'] = ['like', '%'.$searname.'%','OR'];
        }
        $list = $this->model
            ->where($where)
            ->with(['orderData' => function ($query) use($searname){
                if (!empty($searname))
                {
                    $query->whereOr('pay_sn|name','like','%'.$searname.'%');
                }
            },'itemsku','ordergoods' => function ($query) use ($name,$serialNum,$name_keyword) {
                    $query->where('goods_name','like','%'.$name.'%')
                        ->where('partnumber','like','%'.$serialNum.'%')
                        ->where('name_keyword','like','%'.$name_keyword.'%');
            }])
            ->order('create_time desc')
            ->paginate(20, false, ['page' => $page,'query' => [
                'name' => $name,
                'Searname'   => $searname,
                'SerialNum'  => $serialNum,
                'createtime' => $createtime,
                'endtime'    => $endtime,
                'status'     => $status,
                'refundName' => $refundName,
            ]]);

        foreach($list as $key => $val){
            if ($val['item_id'] !== 0)
            {
                $spec = json_decode($val['itemsku']['spec'],true);
                $val['itemsku']['spec'] = $spec;
            }
        }
        
        $rows=$list->items();
        $refund = Config::get(35);
        $refundWhy = json_decode($refund['value'],true);
         foreach ($rows as $k){
             if(!$k['item_id']){
                 $k['item_name']='无';
             }
            //   var_dump($k['goods_name']);exit;
          }
          
         $this->view->assign([
             'total' => $list->total(),
            //  'rows' => $list->items(),
             'page' => $list->render(),
             'searname' => $searname,
             'status'   => $status,
             'refundWhy' => $refundWhy
         ]);
          $this->view->assign('rows',$rows);
         return $this->view->fetch();
        
    }


    public function edit($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {

            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if (empty($params)) {

            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 拒绝退款
     * @param string $ids
     * @throws \think\exception\DbException
     */
    public function refused($ids = '')
    {
        if (!$ids)
        {
            $this->error('参数不能为空','order/sale/index');
        }

        $params = $this->request->param();

        $row   = $this->model->get($ids);

        if (!$row)
        {
            $this->error('数据不存在','order/sale/index');
        }

        if ($params['status'] == 2)
        {
            $orderGoods = OrderGoods::where('id',$row['order_goods_id'])->find();
            $orderData  = OrderModel::where('id',$row['order_id'])->find();
            OrderRefund::create([
                'uid'       => $orderData['uid'],
                'order_id'  => $row['order_goods_id'],
                'refund_sn' => $row['refund_sn'],
                'refund_price'  => $orderGoods['goods_num_price'],
                'refund_amount' => $orderGoods['price'],
                'refund_status' => 0,
                'refund_way'    => 0,
                'create_time'   => time(),
                'refund_integral' => $orderGoods['discounts']
            ]);
        }

        if ($params['status'] == 1)
        {
            $ordergoods = OrderGoods::get($row['order_goods_id']);
            $ordergoodsCount = OrderGoods::where('order_id',$row['order_id'])->count();
            if ($ordergoodsCount > 1)
            {
                $ordergoods->refund_status = 5;
            }else{
                $ordergoods->refund_status = 5;
                OrderModel::where('id',$row['order_id'])->update(['pay_status' => 3]);
            }
            $ordergoods->save();
        }
        if ($params['status'] == 4 )
        {
            OrderModel::where('id',$row['order_id'])->update(['pay_status' => 3]);
        }
        $row->status = $params['status'];
        $row->save();
        $this->success('操作成功','order/sale/index');
    }

    /**
     * 同意退款
     */
    public function refund($ids = '')
    {

            if (!$ids) $this->error('参数不能为空');
            $row   = $this->model->get($ids);
            if (!$row) $this->error('退款信息不存在');

            $orderData = OrderModel::where('id',$row['order_id'])->find();
            $orderGoods = OrderGoods::where('id',$row['order_goods_id'])->find();
            $OrderModel = new OrderModel();

            if ($orderData['user_status'] < 2)
            {
                $response = $OrderModel->goodsMoney($orderGoods['id']);
            }else{
                $response = $OrderModel->goodsIntegral($orderGoods['id']);
            }

            if ($response['status'] == true)
            {
                $time = time();
                $row->status = 6;
                $row->update_time = $time;
                $row->save();
                $this->success($response['msg'],'order/sale/index');
            }else{
                $this->error($response['msg'],'order/sale/index');
            }
    }



}
